package com.sdry.web.controller.base;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sdry.base.BaseController;
import com.sdry.entity.base.Reg;
import com.sdry.entity.base.Staff;
import com.sdry.service.base.RegService;
import com.sdry.utils.DateJsonValueProcessor;
import com.sdry.utils.ExcelUtils;
import com.sdry.utils.ResponseUtil;
/**
 * 
 * @ClassName:regController
 * @Description:地区
 * @Author tdd
 * @Date 2018年4月25日下午5:05:43
 * @version 1.0
 */
@Controller
@RequestMapping("/reg")
public class RegController extends BaseController{
	
	@Resource RegService  regService;
	
	/**
	 * 条件分页查询
	 * @param reg 地区实体类
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/list")
	public String list(Reg reg,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		/*
		 * 条件分页查询内容
		 */
		List<Reg> list = regService.findPageByMution(reg);
		/*
		 * 条件查询总条数
		 */
		Integer total = regService.selectCountByMution(reg);  
		
		/*
		 * 转为json数据传至页面
		 */
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss"));
		//创建result
		JSONObject result = new JSONObject();
		//转json数据
		JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);
		//添加入result
		result.put("rows", jsonArray);
		result.put("total", total);
		//发送result
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 添加地区
	 * @param reg 地区实体类
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/add")
	public String add(Reg reg,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
        //从session中取出用户身份信息
       Staff userSession = (Staff) session.getAttribute("staff");
       String staffname = userSession.getSname();
       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
       String   date   =   sDateFormat.format(new Date());
       reg.setRentry(staffname);
       reg.setRentrytime(date);
		/*
		 * 添加返回id
		 */
		Long rid = regService.add(reg);
		if (null != rid) {
			response.getWriter().print("1");
		}else{
			response.getWriter().print("0");
		}
		return null;
	}
	/**
	 * 根据id查地区
	 * @param rid 地区id
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryById")
	@ResponseBody
	public Reg queryById(Long rid,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		Reg reg = regService.queryById(rid);
		return reg;
	}
	
	/**
	 * 条件查询
	 * @param job 地区实体类
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryAll")
	@ResponseBody
	public List<Reg> queryAllByMution(Reg reg,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		List<Reg> list = regService.queryAllByMution(reg);
		return list;
	}
	
	/**
	 * 修改地区
	 * @param reg 地区实体类
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/update")
	public String update(Reg reg,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
        //从session中取出用户身份信息
       Staff userSession = (Staff) session.getAttribute("staff");
       String staffname = userSession.getSname();
       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
       String   date   =   sDateFormat.format(new Date());
       reg.setRentry(staffname);
       reg.setRentrytime(date);
		/*
		 * 修改返回影响行数
		 */
		Integer count = regService.update(reg);
		if (count >= 1) {
			response.getWriter().print("1");
		}else{
			response.getWriter().print("0");
		}
		return null;
	}
	/**
	 * 多删除
	 * @param ids 地区id累加字符串
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public String delete(String ids,HttpServletRequest request,HttpSession session, HttpServletResponse response) throws Exception{
		System.out.println(ids);
		ids=ids.replace("'",""); 
		/*
		 * 多删除返回影响行数
		 */
		Integer count = regService.deleteIds(ids);
		if (count >= 1) {
			response.getWriter().print("1");
		}else{
			response.getWriter().print("0");
		}
		return null;
	}
	
	
	
	
	/**
	 * 导出当前页数据
	 * @param pageBean
	 * @param limit
	 * @param offset
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExport")
	public void doExport(Reg reg,HttpServletResponse response) throws Exception {
		List<Reg> regs = regService.findPageByMution(reg);
		List<List<String>> lists = regzhuanlist(regs);
		ExcelUtils.export("地区当前数据",namess(), response,lists );
	}	
	/**
	 * 导出所有数据
	 * @param pageBean
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/doExportall")
	public void doExportall(Reg reg,HttpServletRequest request,HttpServletResponse response) throws Exception{
		//未删除
		List<Reg> regs=regService.queryAllByMution(reg);
		List<List<String>> lists = regzhuanlist(regs);
		ExcelUtils.export("地区所有数据",namess(), response,lists);
	}	
	
	
	/**
	 * 导入
	 * @param file
	 * @param request
	 * @param response
	 * @throws URISyntaxException
	 * @throws IOException
	 */
	@RequestMapping("/uplodeFile")
	public void importor(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException{
		   String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/"+file.getOriginalFilename());
		   File newFile=new File(savePath);
		   //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
	       file.transferTo(newFile);
	       //取文件后缀
	       String subfix = savePath.lastIndexOf(".")==-1? "" : savePath.substring(savePath.lastIndexOf(".")+1);
	       System.out.println(subfix);
	       List<List<String>> lists = new ArrayList<>();
	       //获取导入行数
	       List<String> names = names();
	       int num = names.size();
	       if(subfix.equals("xls")){
	    	   lists = ExcelUtils.readXls(savePath, request,num);
	 	   }else if(subfix.equals("xlsx")){
	 		   lists = ExcelUtils.readXlsx(savePath, request,num);
	 	   }else{
	 	   		response.getWriter().print("0");
	 	   }
	       
	       HttpSession session  = request.getSession();
	        //从session中取出用户身份信息
	       Staff userSession = (Staff) session.getAttribute("staff");
	       String staffname = userSession.getSname();;
	       SimpleDateFormat   sDateFormat   =   new   SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
	       String   date   =   sDateFormat.format(new Date());
	       
	       int flag = 1; 
	       for (int i = 0; i < lists.size(); i++) {
	    	   List<String> list = new ArrayList<>();
	    	   list= lists.get(i);
	    
	    	   Reg reg =new Reg();
	    	   reg.setRname(list.get(0));
	    	   reg.setReremarks(list.get(1));
	    	
	    	   int ff = addreg(reg, request, date, staffname);
	    	   reg = null;
	    	   if (ff == 0) {
	    		   flag = 0;
	    		   break;
	    	   }
	       }
	       response.getWriter().print(flag);
	 }
	/**
	 * 导出模板的表头
	 * @return
	 */
	public List<String> names(){
		List<String> list = new ArrayList<>();
		list.add("地区名称");
		list.add("备注");
		return list;
	}
	/**
	 * 导出数据表头
	 * @return
	 */
	public List<String> namess(){
		List<String> list = new ArrayList<>();
		list.add("地区名称");
		list.add("备注");
		list.add("录入人");
		list.add("录入时间");
		return list;
	}
	/**
	 * 根据导出数据表头把List<reg>转List<List<String>>
	 * @param staffs
	 * @return
	 */
	public List<List<String>> regzhuanlist (List<Reg> regs){
		List<List<String>> lists = new ArrayList<>();
		for (Reg reg : regs) {
			List<String> list = new ArrayList<>();
			list.add(reg.getRname());
			list.add(reg.getReremarks());
			list.add(reg.getRentry());
			list.add(reg.getRentrytime());
			lists.add(list);
			list = null;
		}
		return lists;
	}
	/**
	 * 导入数据是的添加方法（如果不满足添加条件，直接过滤）
	 * @param staff
	 * @param request
	 * @param date
	 * @param staffname
	 * @return
	 */
	public int addreg(Reg reg,
			HttpServletRequest request,String date,String staffname){
		int flag = 0;
    	//添加地区
    	//录入人
		reg.setRentry(staffname);
    	//录入时间
		reg.setRentrytime(date);
    	//添加
    	Long id = regService.add(reg);
    	//添加成功
    	if (null != id && id >= 1) {
    		flag = 1;
    	} 
		return flag;
	}
}
